//
//  FourthViewController.m
//  Demo
//
//  Created by 龚碧容 on 2017/9/15.
//  Copyright © 2017年 hwd. All rights reserved.
//

#import "FourthViewController.h"
#import "QLMUserTableCell.h"
#import "QLMUserHeaderView.h"
#import "QLMEditLocationVC.h"
#import "QLMUserInfoDetailVC.h"
#import "QLMClearCacheVC.h"
#import "QLMDeviceListVC.h"
#import "QLMBXOrderListVC.h"

#import <JPUSHService.h>
#import <UMSocialCore/UMSocialCore.h>
#import <UShareUI/UShareUI.h>

#import "QLMDetailAddressVC.h"
#import "QLMVipInfoVC.h"
#import "QLMXmDouVC.h"

#import "CreatQRCodeAndBarCode.h"
#import "QLMImageMaginfication.h"
#import "QLMInvoicesViewController.h"

@interface FourthViewController ()<UIGestureRecognizerDelegate,UITableViewDelegate,UITableViewDataSource,UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>{
    NSArray *tipsArray;
    NSArray *imagenameArray;
    QLMUserHeaderView *userView;
    NSString *tmpDou;
    NSString *invitationCode;
    
    NSString *integrationNew;
    NSString *vipLevel;
    NSString *vipPoint;
    NSString *vipNumber;
    
    NSString *vipPointSatrt;
    NSString *vipPointEnd;
    NSString *vipArrivalTime;
    
    UIView *coverView;
    UIView *selectAlertView;
}

@property (nonatomic,strong) UITableView *tableview;
@property (nonatomic,strong) NSString *sizeStr;

@end

@implementation FourthViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationController.view.backgroundColor=UIColorFromRGB(0xf5f5f5);
    self.title=@"我的";
    
    tipsArray=[NSArray arrayWithObjects:@"我的订单",@"地址管理",@"设备管理",@"礼品兑换",@"应用分享",@"绑定邀请码",@"发票添加",nil];//
    imagenameArray=[NSArray arrayWithObjects:@"orderIcon",@"01",@"02",@"lw_icon",@"04",@"orderIcon",@"fo_icon",nil];//
    
    _tableview=[[UITableView alloc] initWithFrame:CGRectMake(0, IOS11_OR_LATER_SPACE(24), kScreen_width, kScreen_height-49-IOS11_OR_LATER_SPACE(34+24)) style:UITableViewStyleGrouped];
    _tableview.backgroundColor=[UIColor clearColor];
    _tableview.delegate=self;
    _tableview.dataSource=self;
    _tableview.tableFooterView=[UIView new];
    [self.view addSubview:_tableview];
    
    if (@available(iOS 11.0, *)) {
        _tableview.contentInsetAdjustmentBehavior=UIScrollViewContentInsetAdjustmentNever;
    } else {
        // Fallback on earlier versions
        self.automaticallyAdjustsScrollViewInsets=NO;
    }
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pushToLoginVC) name:@"pushTologinAction" object:nil];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden=YES;

    if ([[UserManager sharedManager] isUserLogin]) {
        [self reuqestUserInfoData];
    }else{
        [self updateMainUI];
    }
    [MobClick beginLogPageView:self.title];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:self.title];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 更新UI
- (void)updateMainUI{
    userView.userheaderImaView.image=[UIImage imageNamed:@"header"];
    [userView.mynameBtn setTitle:@"请登录" forState:UIControlStateNormal];
    userView.myphoneLable.text=@"";
    userView.lineImaView.hidden=YES;
    userView.vipBtn.hidden=YES;
    userView.qrCodeButton.hidden=YES;
    [_tableview reloadData];
}

#pragma mark - 请求数据
- (void)reuqestUserInfoData{
    NSString *token=[[NSUserDefaults standardUserDefaults] objectForKey:kLoginToken];
    NSDictionary *tokenDic=[NSDictionary dictionaryWithObjectsAndKeys:token,@"token", nil];
    
    [self.view makeToastActivity:CSToastPositionCenter];
    [ClientTool postUrlPath:@"/user/userInfo" withParamers:nil andBody:tokenDic
                    success:^(id responseObject){
                        [self.view hideToastActivity];
                        NSInteger code = [[responseObject objectForKey:@"flag"] integerValue];
                        if (code == 1) {
                            
                            NSString *pathName=[NSString stringWithFormat:@"%@%@",kBaseURL,[[responseObject[@"data"] objectForKey:@"user"] objectForKey:@"userIcon"]];
                            
                            [userView.userheaderImaView sd_setImageWithURL:[NSURL URLWithString:pathName] placeholderImage:[UIImage imageNamed:@"header"]];
                            
                            NSShadow *shadow=[[NSShadow alloc] init];
                            shadow.shadowColor=[UIColor lightGrayColor];
                            shadow.shadowOffset=CGSizeMake(0, 0);
                            shadow.shadowBlurRadius=6.0;
                            
                            NSString *huiyuanStr=[NSString stringWithFormat:@"会员ID:%@",[[responseObject[@"data"] objectForKey:@"user"] objectForKey:@"vipNumber"]];
                            NSAttributedString *attributedStr=[[NSAttributedString alloc] initWithString:huiyuanStr attributes:@{NSShadowAttributeName:shadow}];
                            
                            NSString *nameStr=[[responseObject[@"data"] objectForKey:@"user"] objectForKey:@"userName"];
                            NSAttributedString *nameAttributedStr=[[NSAttributedString alloc] initWithString:nameStr attributes:@{NSShadowAttributeName:shadow}];
                            
                            [userView.mynameBtn setAttributedTitle:nameAttributedStr forState:UIControlStateNormal];
                            userView.myphoneLable.attributedText=attributedStr;
                            
                            vipNumber=[NSString stringWithFormat:@"%@",[[responseObject[@"data"] objectForKey:@"user"] objectForKey:@"vipNumber"]];
                            NSString *jrUserid=[NSString stringWithFormat:@"%@",[[responseObject[@"data"] objectForKey:@"user"] objectForKey:@"jrUserId"]];
                            [[NSUserDefaults standardUserDefaults] setObject:jrUserid forKey:kJrUserId];
                            [[NSUserDefaults standardUserDefaults] setObject:vipNumber forKey:kVipNumber];
                            
                            vipPoint=[NSString stringWithFormat:@"%@",[responseObject[@"data"] objectForKey:@"vipPoint"]];
                            
                            vipPointEnd=[NSString stringWithFormat:@"%@",[responseObject[@"data"] objectForKey:@"vipPointEnd"]];
                            vipPointSatrt=[NSString stringWithFormat:@"%@",[responseObject[@"data"] objectForKey:@"vipPointSatrt"]];
                            vipArrivalTime=[NSString stringWithFormat:@"%@",[responseObject[@"data"] objectForKey:@"vipArrivalTime"]];
                            
                            tmpDou=[[responseObject[@"data"] objectForKey:@"user"] objectForKey:@"xiaomabeenTotal"];
                            if (![ClientTool isNull:tmpDou]) {
                                tmpDou=@"0";
                            }
                            NSString *douNum = [NSString stringWithFormat:@"小马豆:%@",tmpDou];
                            [userView.douBtn setTitle:douNum forState:UIControlStateNormal];
                            
                            invitationCode=[[responseObject[@"data"] objectForKey:@"user"] objectForKey:@"invitationCode"];
                            
                            vipLevel=[NSString stringWithFormat:@"%@",[[responseObject[@"data"] objectForKey:@"user"] objectForKey:@"vipLevel"]];
                            integrationNew=[NSString stringWithFormat:@"%@",[[responseObject[@"data"] objectForKey:@"user"] objectForKey:@"integrationNew"]];

                            userView.vipBtn.hidden=NO;
                            userView.lineImaView.hidden=NO;
                            userView.qrCodeButton.hidden=NO;

                            switch ([vipLevel integerValue]) {
                                case 1:
                                    [self _setUpdateImageView:@"ptk"];
                                    break;
                                case 2:
                                    [self _setUpdateImageView:@"zzk"];
                                    break;
                                case 3:
                                    [self _setUpdateImageView:@"sjk"];
                                    break;
                                case 4:
                                    [self _setUpdateImageView:@"hjk"];
                                    break;
                                case 5:
                                    [self _setUpdateImageView:@"bjk"];
                                    break;
                                default:
                                    break;
                            }

                        }else{
                            ETToast(responseObject[@"msg"]);
                        }
                    }failure:^(NSError *error){
                        [self.view hideToastActivity];
                        ETToast(@"服务器连接失败");
                    }
     ];
}

- (void)_setUpdateImageView:(NSString *)preStr{
    [userView.vipBackImaView setImage:[UIImage imageNamed:preStr]];
}

- (void)showBottomNormalView{
    [UMSocialShareUIConfig shareInstance].sharePageGroupViewConfig.sharePageGroupViewPostionType = UMSocialSharePageGroupViewPositionType_Bottom;
    
    [UMSocialShareUIConfig shareInstance].sharePageScrollViewConfig.shareScrollViewPageItemStyleType = UMSocialPlatformItemViewBackgroudType_IconAndBGRoundAndSuperRadius;

    [UMSocialUIManager showShareMenuViewInWindowWithPlatformSelectionBlock:^(UMSocialPlatformType platformType, NSDictionary *userInfo) {
        [self shareImageURLToPlatformType:platformType];
    }];
}

//分享网络图片
- (void)shareImageURLToPlatformType:(UMSocialPlatformType)platformType{
    
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:@"小马快修" descr:@"中国领先的工程机械共享赋能服务平台" thumImage:[UIImage imageNamed:@"shareIcon"]];
    shareObject.webpageUrl=@"http://text.sevalo.com:8080/down/d.html";
    messageObject.shareObject = shareObject;
    
    //调用分享接口
    [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
        if (error) {
            UMSocialLogInfo(@"Share fail with error %@",error);
        }else{
            if ([data isKindOfClass:[UMSocialShareResponse class]]) {
                UMSocialShareResponse *resp = data;
                UMSocialLogInfo(@"response message is %@",resp.message);
                UMSocialLogInfo(@"response originalResponse data is %@",resp.originalResponse);
            }else{
                UMSocialLogInfo(@"response data is %@",data);
            }
        }
        [self alertWithError:error];
    }];
}

- (void)alertWithError:(NSError *)error{
    NSString *result = nil;
    if (!error) {
        result = [NSString stringWithFormat:@"分享成功"];
    }else{
        NSMutableString *str = [NSMutableString string];
        if (error.userInfo) {
            for (NSString *key in error.userInfo) {
                [str appendFormat:@"%@ = %@\n", key, error.userInfo[key]];
            }
        }
        if (error) {
            result = [NSString stringWithFormat:@"分享失败错误信息: %d\n%@",(int)error.code, str];
        }else{
            result = [NSString stringWithFormat:@"分享失败"];
        }
    }
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"分享"
                                                    message:result
                                                   delegate:nil
                                          cancelButtonTitle:@"确定"
                                          otherButtonTitles:nil];
    [alert show];
}

#pragma mark - Action
- (void)pushToOrderListVC{
    QLMBXOrderListVC *bxOrderVC=[QLMBXOrderListVC new];
    self.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:bxOrderVC animated:YES];
    self.hidesBottomBarWhenPushed=NO;
}

- (void)pushToEditLocationVC{
    QLMEditLocationVC *editVC=[QLMEditLocationVC new];
    self.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:editVC animated:YES];
    self.hidesBottomBarWhenPushed=NO;
}

- (void)pushtoDeviceVC{
    QLMDeviceListVC *deviceVC=[QLMDeviceListVC new];
    self.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:deviceVC animated:YES];
    self.hidesBottomBarWhenPushed=NO;
}

- (void)changePassportButtonAction:(BOOL)isBindBool{
    QLMForgetViewController *changeVC=[QLMForgetViewController new];
    changeVC.isBindBool=isBindBool;
    
    if (isBindBool) {
        if ([ClientTool isNull:invitationCode]&&invitationCode.length!=0) {
            changeVC.invitationCodeStr=invitationCode;
        }
    }

    self.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:changeVC animated:YES];
    self.hidesBottomBarWhenPushed=NO;
}

- (void)pushToLoginVC{
    if (![[UserManager sharedManager] isUserLogin]){
        [self presentaLoginVC];
    }
}

- (void)presentaLoginVC{
    QLMLoginViewController *loginController = [QLMLoginViewController new];
    loginController.resultBlock=^(BOOL success){};
    QLMCustomNavCtr *nav=[[QLMCustomNavCtr alloc] initWithRootViewController:loginController];
    [self.navigationController presentViewController:nav animated:YES completion:nil];
}


- (void)pushToUserInfoDetailVC{
    QLMUserInfoDetailVC *userinfoVC=[QLMUserInfoDetailVC new];
    self.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:userinfoVC animated:YES];
    self.hidesBottomBarWhenPushed=NO;
}

- (void)pushToInvoiceVC{
    QLMInvoicesViewController *invoiceVC=[QLMInvoicesViewController new];
    self.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:invoiceVC animated:YES];
    self.hidesBottomBarWhenPushed=NO;
}

- (void)settingButtonAction:(UITapGestureRecognizer *)gesture{
    if (![[UserManager sharedManager] isUserLogin]) {
        [self pushToLoginVC];
        return;
    }
    [self selImageBtnAction];
}

- (CIImage *)generateBarCodeImage:(NSString *)source{
    // iOS 8.0以上的系统才支持条形码的生成，iOS8.0以下使用第三方控件生成
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        // 注意生成条形码的编码方式
        NSData *data = [source dataUsingEncoding:NSASCIIStringEncoding];
        CIFilter *filter = [CIFilter filterWithName:@"CICode128BarcodeGenerator"];
        [filter setValue:data forKey:@"inputMessage"];
        // 设置生成的条形码的上，下，左，右的margins的值
        [filter setValue:[NSNumber numberWithInteger:0] forKey:@"inputQuietSpace"];
        return filter.outputImage;
    }else{
        return nil;
    }
}

- (UIImage *)resizeCodeImage:(CIImage *)image withSize:(CGSize)size{
    if (image) {
        CGRect extent = CGRectIntegral(image.extent);
        CGFloat scaleWidth = size.width/CGRectGetWidth(extent);
        CGFloat scaleHeight = size.height/CGRectGetHeight(extent);
        size_t width = CGRectGetWidth(extent) * scaleWidth;
        size_t height = CGRectGetHeight(extent) * scaleHeight;
        CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceGray();
        CGContextRef contentRef = CGBitmapContextCreate(nil, width, height, 8, 0, colorSpaceRef, (CGBitmapInfo)kCGImageAlphaNone);
        CIContext *context = [CIContext contextWithOptions:nil];
        CGImageRef imageRef = [context createCGImage:image fromRect:extent];
        CGContextSetInterpolationQuality(contentRef, kCGInterpolationNone);
        CGContextScaleCTM(contentRef, scaleWidth, scaleHeight);
        CGContextDrawImage(contentRef, extent, imageRef);
        CGImageRef imageRefResized = CGBitmapContextCreateImage(contentRef);
        CGContextRelease(contentRef);
        CGImageRelease(imageRef);
        return [UIImage imageWithCGImage:imageRefResized];
    }else{
        return nil;
    }
}

- (void)showQRCodeAction{
    [self aSetupcreatAlertView];
}

- (void)tapDismiss{
    [coverView removeFromSuperview];
    [selectAlertView removeFromSuperview];
}

- (void)aSetupcreatAlertView{
    
    coverView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    coverView.backgroundColor = [UIColor blackColor];
    coverView.alpha = 0.3;
    coverView.userInteractionEnabled=YES;
    [kWindow addSubview:coverView];
    UITapGestureRecognizer *tap123=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapDismiss)];
    [coverView addGestureRecognizer:tap123];
    
    selectAlertView = [[UIView alloc] init];
    selectAlertView.frame = CGRectMake(kScreen_width/2-305/2,kScreen_height-64-IOS11_OR_LATER_SPACE(24),305,405);
    selectAlertView.backgroundColor = [UIColor clearColor];
    selectAlertView.center=coverView.center;
    [kWindow addSubview:selectAlertView];
    
    UIImageView *topView=[[UIImageView alloc] init];
    topView.frame = CGRectMake(0,0,305,405);
    topView.image = [UIImage imageNamed:@"tmk"];
    topView.userInteractionEnabled=YES;
    [selectAlertView addSubview:topView];
    
    UIImageView *codeImageView=[[UIImageView alloc] initWithFrame:CGRectMake(20, 60, 305-40,60)];
    codeImageView.userInteractionEnabled=YES;
    CIImage *ciImage = [self generateBarCodeImage:vipNumber];
    UIImage *image = [self resizeCodeImage:ciImage withSize:CGSizeMake(kScreen_width-80,60)];
    codeImageView.image = image;
    codeImageView.tag=21;
    [selectAlertView addSubview:codeImageView];
    
    UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(imageViewClickAction:)];
    [codeImageView addGestureRecognizer:tap1];
    
    UILabel *_vipNumLable = [[UILabel alloc]initWithFrame:CGRectMake(20, 125, 180, 21)];
    _vipNumLable.text = vipNumber;
    _vipNumLable.textAlignment=NSTextAlignmentLeft;
    _vipNumLable.font = [UIFont boldSystemFontOfSize:15.0f];
    _vipNumLable.textColor=[UIColor darkGrayColor];
    _vipNumLable.backgroundColor = [UIColor whiteColor];
    [selectAlertView addSubview:_vipNumLable];
    
    UIImageView *qrcodeImageView=[[UIImageView alloc] initWithFrame:CGRectMake(305/2-90, 180, 180,180)];
    qrcodeImageView.userInteractionEnabled=YES;
    qrcodeImageView.image=[CreatQRCodeAndBarCode qrImageWithString:vipNumber
                                                            size:CGSizeMake(180,180)
                                                           color:[UIColor darkGrayColor]
                                                 backGroundColor:[UIColor whiteColor]];
    [selectAlertView addSubview:qrcodeImageView];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(imageViewClickAction:)];
    [qrcodeImageView addGestureRecognizer:tap];
}

- (void)imageViewClickAction:(UITapGestureRecognizer *)sender{
    if (sender.view.tag==21) {
        [QLMImageMaginfication showImageBrowserWithImageView:(UIImageView *)sender.view labelStr:vipNumber labelHidden:NO];
    }else{
        [QLMImageMaginfication showImageBrowserWithImageView:(UIImageView *)sender.view labelStr:nil labelHidden:YES];
    }
}

#pragma mark - UITableViewData source
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section==0) {
        return 245*(kScreen_width/359)+5+50+20;
    }
    return 5;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UIView *headerView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreen_width, 120)];
    headerView.backgroundColor=[UIColor clearColor];
    if (section==0) {
        headerView.userInteractionEnabled=YES;
        UIView *backview=[[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreen_width, 245*(kScreen_width/359)+50+20)];
        backview.backgroundColor=kNavigationBarColor;
        [headerView addSubview:backview];
        
        userView=[[QLMUserHeaderView alloc] initWithFrame:CGRectMake(0, 0, kScreen_width, 245*(kScreen_width/359)+50+20)];
        userView.backgroundColor=[UIColor clearColor];
        userView.userInteractionEnabled=YES;
        [userView.settingButton addTarget:self action:@selector(pushToUserInfoDetailVC) forControlEvents:UIControlEventTouchUpInside];
        [backview addSubview:userView];
        
        if ([[UserManager sharedManager] isUserLogin]) {
            userView.vipBtn.hidden=NO;
            userView.lineImaView.hidden=NO;
            userView.qrCodeButton.hidden=NO;
        }else{
            userView.vipBtn.hidden=YES;
            userView.lineImaView.hidden=YES;
            userView.qrCodeButton.hidden=YES;
        }
        
        [userView.vipBtn addTarget:self action:@selector(pushToVipInfoVC) forControlEvents:UIControlEventTouchUpInside];
        
        UITapGestureRecognizer *tapImage=[[UITapGestureRecognizer alloc] init];
        [tapImage addTarget:self action:@selector(settingButtonAction:)];
        userView.userheaderImaView.userInteractionEnabled=YES;
        [userView.userheaderImaView addGestureRecognizer:tapImage];
        
        [userView.qrCodeButton addTarget:self action:@selector(showQRCodeAction) forControlEvents:UIControlEventTouchUpInside];
        [userView.mynameBtn addTarget:self action:@selector(pushToLoginVC) forControlEvents:UIControlEventTouchUpInside];
        [userView.douBtn addTarget:self action:@selector(pushToDouVC:) forControlEvents:UIControlEventTouchUpInside];
        userView.douBtn.tag=222;
        [userView.youhuiBtn addTarget:self action:@selector(pushToDouVC:) forControlEvents:UIControlEventTouchUpInside];
        userView.youhuiBtn.tag=223;
    }
    return headerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.1;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return nil;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section==0) {
        return 3;
    }
    return 4;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 60;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    QLMUserTableCell *usercell=[QLMUserTableCell cellWithTableView:tableView];
    
    if (indexPath.section==0) {
        usercell.tipsLabel.text=tipsArray[indexPath.row];
        usercell.iconImageView.image=[UIImage imageNamed:imagenameArray[indexPath.row]];
    }else{
        usercell.tipsLabel.text=tipsArray[indexPath.row+3];
        usercell.iconImageView.image=[UIImage imageNamed:imagenameArray[indexPath.row+3]];
    }
    
    return usercell;
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if ([[UserManager sharedManager] isUserLogin]) {//判断是否登录
        
        if (indexPath.section==0) {
            if (indexPath.row==0){
                [self pushToOrderListVC];
            }else if (indexPath.row==1){
                [self pushToEditLocationVC];
            }else if (indexPath.row==2){
                [self pushtoDeviceVC];
            }
        }else{
            if (indexPath.row==0){

                [self reuqestWebInfoData];
                
            }else if (indexPath.row==1){
                [self showBottomNormalView];
            }else  if (indexPath.row==2){
                [self changePassportButtonAction:YES];
            }else{
                [self pushToInvoiceVC];
            }
        }

    }else{
        [self pushToLoginVC];
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
- (void)pushToDouVC:(UIButton *)btn{
    if (btn.tag==222) {
        
        if ([[UserManager sharedManager] isUserLogin]) {
            QLMXmDouVC *scanVC=[QLMXmDouVC new];
            scanVC.xiaomabeeStr=[NSString stringWithFormat:@"%@",tmpDou];
            self.hidesBottomBarWhenPushed=YES;
            [self.navigationController pushViewController:scanVC animated:YES];
            self.hidesBottomBarWhenPushed=NO;
        }else{
            [self pushToLoginVC];
        }
    }else{
        ETToast(@"此功能正在开发中，敬请期待！");
    }
}

- (void)pushToVipInfoVC{
    QLMVipInfoVC *vipVC=[QLMVipInfoVC new];
    vipVC.integrationNew=integrationNew;
    vipVC.vipLevel=vipLevel;
    vipVC.vipPoint=vipPoint;
    
    vipVC.vipPointSatrt=vipPointSatrt;
    vipVC.vipPointEnd=vipPointEnd;
    vipVC.vipArrivalTime=vipArrivalTime;
    
    self.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:vipVC animated:YES];
    self.hidesBottomBarWhenPushed=NO;
}


#pragma mark - image picker
- (void)selImageBtnAction{
    UIActionSheet *cameraSheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"相册",@"拍照", nil];
    cameraSheet.actionSheetStyle = UIActionSheetStyleAutomatic;
    [cameraSheet showInView:self.view];
}

- (void)uploadImageData:(NSMutableArray *)userHeaderImageArray{
    ETToast(@"正在上传图片");
    NSString *token=[[NSUserDefaults standardUserDefaults] objectForKey:kLoginToken];
    NSMutableDictionary *tokenDic=[NSMutableDictionary dictionaryWithObjectsAndKeys:token,@"token", nil];
    NSString *urlString=[NSString stringWithFormat:@"%@%@",kBaseURL,@"/rest/appUpload"];
    [ClientTool postUrlPath:urlString withParamers:tokenDic type:userHeaderImageArray success:^(id responseObject) {
        [self.view hideToastActivity];
        NSInteger status = [[responseObject objectForKey:@"flag"] integerValue];
        if (status == 1){
            [self editUserImageData:responseObject[@"list"][0]];
        }else{
            ETToast([responseObject objectForKey:@"msg"]);
        }
    } failure:^(NSError *error) {
        [self.view hideToastActivity];
        ETToast(@"服务器连接失败");
    }];
}

- (void)editUserImageData:(NSString *)imageurl{
    
    NSString *token=[[NSUserDefaults standardUserDefaults] objectForKey:kLoginToken];
    NSMutableDictionary *tokenDic=[NSMutableDictionary dictionaryWithObjectsAndKeys:token,@"token", nil];

    NSMutableDictionary *paramerDic=[NSMutableDictionary dictionary];
    [paramerDic setObject:[NSString stringWithFormat:@"%@",imageurl] forKey:@"userIcon"];
    
    [self.view makeToastActivity:CSToastPositionCenter];
    [ClientTool postUrlPath:@"/user/edit" withParamers:paramerDic andBody:tokenDic success:^(id responseObject) {
        [self.view hideToastActivity];
        ETToast(responseObject[@"msg"]);
    } failure:^(NSError *error) {
        [self.view hideToastActivity];
        ETToast(@"服务器连接失败");
    }];
}

#pragma mark - UIActionSheet delegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    if(buttonIndex == 2){
        return;
    }else{
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        if(buttonIndex == 0){
            picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        }else if(buttonIndex == 1){//拍照
            if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
                return;
            }
            picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        }
        picker.delegate = self;
        [self presentViewController:picker animated:YES completion:nil];
    }
}

#pragma mark - UIImagepicker delegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    [picker dismissViewControllerAnimated:YES completion:^{
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
        userView.userheaderImaView.image=image;
        NSMutableArray *tmpArray=[NSMutableArray array];
        [tmpArray addObject:image];
        [self uploadImageData:tmpArray];
    }];
}

- (void)reuqestWebInfoData{
    NSString *token=[[NSUserDefaults standardUserDefaults] objectForKey:kLoginToken];
    NSDictionary *tokenDic=[NSDictionary dictionaryWithObjectsAndKeys:token,@"token", nil];
    
    [self.view makeToastActivity:CSToastPositionCenter];
    [ClientTool postUrlPath:@"/rest/shop/index" withParamers:nil andBody:tokenDic
                    success:^(id responseObject){
                        [self.view hideToastActivity];
                        QLMDetailAddressVC *webVC=[QLMDetailAddressVC new];
                        webVC.htmlurlStr=responseObject[@"url"];
                        webVC.title=@"礼品兑换";
                        self.hidesBottomBarWhenPushed=YES;
                        [self.navigationController pushViewController:webVC animated:YES];
                        self.hidesBottomBarWhenPushed=NO;
                    }failure:^(NSError *error){
                        [self.view hideToastActivity];
                        ETToast(@"服务器连接失败");
                    }
     ];
}

@end
